/*******************************************************************/
/*    Common JS developed by Paolo Moretti (littlebrown#gmail.com) */
/*******************************************************************/

var path = String(window.location).split('/');
if(
   	path[path.length-2] == 'conf' || 
	path[path.length-2] == 'inc' || 
	path[path.length-2] == 'conf'
) var pathDir = '../';
else var pathDir = '';
document.write('<script type="text/javascript" src="'+pathDir+'js/prototype.js"></script>');
document.write('<script type="text/javascript" src="'+pathDir+'js/scriptaculous.js"></script>');
document.write('<script type="text/javascript" src="'+pathDir+'js/Console.js"></script>');
document.write('<script type="text/javascript" src="'+pathDir+'js/calendar/scal.js"></script>');
document.write('<script type="text/javascript" src="'+pathDir+'js/Animations.js"></script>');
//document.write('<script type="text/javascript" src="'+pathDir+'js/tinymce/tiny_mce.js"></script>');
document.write('<script type="text/javascript" src="'+pathDir+'js/nicEditor/nicEdit.js"></script>');

/**********************/
/* CLASSE GENERALE FF */
/**********************/

var FF = {
	// On load
	ClickActions: new Array(),
	
	initPage: function() {
		
		Event.observe(document.body, 'click', FF.EventManager.runDocumentClickAction);
		Event.observe(window, 'keypress', FF.EventManager.runKeyMapper);
		FF.EventManager.addDocumentClickAction('if(Event.element(e) && Element.ancestors(Event.element(e)).indexOf($("toolBar")) == -1) FF.closeToolbarItem(FF.activeMenu)');
		
		if($('loader')) new Effect.Fade('loader', {from: .85, to:0, duration: .5, afterFinishInternal: function() {
			Element.remove($('loader'));
		}});
		
		this.setWindowProperties();
		this.setPageToolbar();
		
		// Caricamento della pagina
		var fadeLayer = Builder.node('DIV', {id: 'fadeLayerWrapper', style: 'position: absolute; top: 200px; left:200px; width:300px; height:200px; background:#000; display:none; z-index:999'});
		Element.setOpacity(fadeLayer, 0);
		$$('BODY')[0].appendChild(fadeLayer);
		
		// Grafica per i tabs
		var tabs = $$('div.tabStyle');
		if(tabs.length > 0) {
			for(var i=0; i<tabs.length; i++) {
				tabs[i].appendChild(Builder.node('b', {style: 'width:1px; height:1px; overflow:hidden; line-height:1px; background:#FFF; position:absolute; top:0; left:0; display: block'}));
				tabs[i].appendChild(Builder.node('i', {style: 'width:1px; height:1px; overflow:hidden; line-height:1px; background:#FFF; position:absolute; top:0; right:0'}));
			}
		}

	},
	
	log: function(t) {
		new Ajax.Request('inc/ajaxRequests.php?action=_log&logText='+t, {method: 'get'});
	},
	
	popup: function(url, name, w, h) {
		var newWindow = window.open(url, name, 'height='+h+',width='+w);
		if (window.focus) newWindow.focus();
	},
	
	closePageLogger: function(logElement) {
		Element.hide(logElement);
		new Ajax.Request('inc/ajaxRequests.php?action=deletePageLogger', {method: 'get'});
	},	
	
	setWindowProperties: function() {
		if($('contentWrapper') && $('contentHeader')) {
			FF.visual.checkContentSize();
			window.onresize = function() { FF.visual.checkContentSize(); }
		}
		
	},
	
	addToolbarItem: function(opt) {
		
	},
	
	setPageToolbar: function() {
		if($$('#toolBar UL.FirstLevel')[0]) {
			if($$('#toolBar UL.FirstLevel')[0]) {
				var fl = $A(Element.cleanWhitespace($$('#toolBar UL.FirstLevel')[0]).childNodes);
				fl.each(function(e, i){
					e.onclick = function() {
						if(FF.activeMenu == this) FF.closeToolbarItem(this); 
						else FF.openToolbarItem(this); 
					}
				});
			}
		}
	},
	
	closeToolbarItem: function(e) {
		this.activeMenu = false;
		if(e) {
			if(Element.cleanWhitespace(e).lastChild) Element.cleanWhitespace(e).lastChild.style.display = 'none';
			Element.removeClassName(e, 'on');
			e.onclick = function() {
				if(FF.activeMenu == this) FF.closeToolbarItem(this); 
				else FF.openToolbarItem(this); 
			}
		}
	},
	
	openToolbarItem: function(e) {
		if($$('#toolBar UL.FirstLevel')[0]) {
			var fl = $A(Element.cleanWhitespace($$('#toolBar UL.FirstLevel')[0]).childNodes);
			fl.each(function(e, i){
				FF.closeToolbarItem(e);
				e.onmouseover = function() {
					FF.openToolbarItem(this);
				}
			});
		}
		e.onclick = function(){};
		FF.activeMenu = e;
		if(e) {
			var sl = Element.cleanWhitespace(e).lastChild;
			sl.style.display = 'block';
			Element.addClassName(e, 'on');
			
		}
	},
	
	getElementSize: function(id) {
		var sizes = new Array();
		sizes['w'] = $(id).offsetWidth;
		sizes['h'] = $(id).offsetHeight;
		sizes['l'] = $(id).offsetLeft;
		sizes['t'] = $(id).offsetTop;
		return sizes;
	}
}


FF.visual = {
	
	showFogLayer: function() {
		
	},
	
	setActiveFilter: function(obj) {
		this.disableTabs();
		if(!Element.hasClassName(obj.parentNode, 'on')) Element.addClassName(obj.parentNode, 'on');
	},
	
	disableTabs: function() {
		$$('.tabStyle').each(function(e){
			Element.removeClassName(e, 'on');
		});
	},
	
	report: function(txt, type) {
		FF.log(txt);
		if($('tabContainer')) {
			var report = Builder.node('DIV', {className: 'tabStyle pageLogger'}, [
				Builder.node('A', {href: '#', onclick: 'Element.remove(this.parentNode)'}, 'X'), txt,
				Builder.node('b', {style: 'width:1px; height:1px; overflow:hidden; line-height:1px; background:#FFF; position:absolute; top:0; left:0; display: block'}),
				Builder.node('i', {style: 'width:1px; height:1px; overflow:hidden; line-height:1px; background:#FFF; position:absolute; top:0; right:0'})
			]);
			new Insertion.Before('tabContainerClearer', report);
			var intID = setInterval(function(){
				new Effect.Fade(report);
				clearInterval(intID);
			}, 5000);
		}
	},
	
	enlargeViewport: function(menuWidth, headerHeight) {
		this.viewportStatus = "enlarged";
		this.menuWidth = menuWidth;
		this.headerHeight = headerHeight;
		parent.document.getElementById('FFcontentWindow').setAttribute('cols', "0,*");
		parent.document.getElementById('FFWindow').setAttribute('rows', "0,*"); 
	},
	
	resetViewport: function() {
		this.viewportStatus = "normal";
		parent.document.getElementById('FFcontentWindow').setAttribute('cols', this.menuWidth+",*");
		parent.document.getElementById('FFWindow').setAttribute('rows', this.headerHeight+",*"); 
	},
	
	setWindowControllers: function(ctrl) {
		Event.observe($(ctrl), 'mouseover', function() {this.style.cursor = 'w-resize';});
		Event.observe($(ctrl), 'mousedown', FF.visual.doResize);
	},
	
	doResize: function(ev) {
		Event.element(ev).style.width = '30px';
		parent.document.getElementById('FFcontentWindow').setAttribute('cols', (self.innerWidth + 15)+",*");
		FF.visual.posx = Event.pointerX(ev);
		Event.observe(Event.element(ev), 'mousemove', FF.visual.setResize);
		Event.observe(Event.element(ev), 'mouseup', FF.visual.stopResize);
	},
	
	stopResize: function(ev) {
		Event.element(ev).style.width = '5px';
		Event.stopObserving(Event.element(ev), 'mousemove', FF.visual.setResize);
		new Ajax.Request('inc/ajaxRequests.php?action=saveViewportUI&menuCol='+FF.visual.viewportUI, {
			method: 'get',
			onComplete: FF.visual.stopResize_handler
		});
	},
	
	stopResize_handler: function(ajax) {
		parent.content.externalCall('FF.visual.report("UI settings saved!")');
	},
	
	setResize: function(ev) {
		var menuWin_w = self.innerWidth;
		var contentWin_w = parent.window.content.innerWidth;
		var newMenuW = menuWin_w - (FF.visual.posx - Event.pointerX(ev));
		var newContentW = contentWin_w + (FF.visual.posx - Event.pointerX(ev));
		parent.document.getElementById('FFcontentWindow').setAttribute('cols', newMenuW+","+newContentW);
		FF.visual.viewportUI = newMenuW;
		FF.visual.posx = Event.pointerX(ev);
	},
	
	resizePopup: function(popupId, x, y, d) {
		if(x) Animations.xscale($('popupWrapper'), x, d);
		if(y) Animations.yscale($('popupWrapper'), y, d);
	},
	
	hideFogLayer: function() {
		Element.setOpacity('contentWrapper', 1);
		$('contentWrapper').disabled = false;
	},
	
	createPopup: function() {
		if(!$('popupWrapper'))  {
			var popup = Builder.node('DIV', {id: 'popupWrapper', style: 'position: absolute; top: 1px; left:1px; width:1px; height:1px; background:#FFF; z-index: 9999'});
			Element.setOpacity(popup, 0);
			return popup;
		} else return $('popupWrapper');
	},
	
	checkContentSize: function() {
		
		var wh = this.getWindowSize();
			
		$('contentWrapper').style.width = this.windowWidth-6 + 'px';
		$('contentWrapper').style.height = (this.windowHeight - $('contentHeader').offsetHeight - 5) + 'px';
		
	},
	
	getWindowSize: function() {
		if( typeof( window.innerWidth ) == 'number' ) {
			//Non-IE
			this.windowWidth = window.innerWidth;
			this.windowHeight = window.innerHeight;
		} else if (document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
			//IE 6+ in 'standards compliant mode'
			this.windowWidth = document.documentElement.clientWidth;
			this.windowHeight = document.documentElement.clientHeight;
		} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
			//IE 4 compatible
			this.windowWidth = document.body.clientWidth;
			this.windowHeight = document.body.clientHeight;
		}
	},
	
	openMenuRow: function(id) {
		if($(id).style.display && $(id).style.display == 'block') $(id).style.display = 'none';
		else {
			$(id).style.display = 'block';
		}
	}
	
}

FF.contents = {
	
	table: '',		// Settata dal PHP su content.php
	selectedRows: new Array(),
	
	loading: function(status) {
		if(status) {
			var fog = Builder.node('div', {id: 'loader'});
			document.body.appendChild(fog);
			Element.setOpacity('loader', .85);
		}
	},
	
	checkRow: function (obj, status) {
		var row = obj.parentNode.parentNode;
		if(status) {
			obj.checked = true;
			Element.addClassName(row, 'selected');
			this.selectedRows.push(row.id);
		} else {
			obj.checked = false;
			Element.removeClassName(row, 'selected');
			this.selectedRows = this.selectedRows.without(row.id);
		}
		this.checkSelection();
	},
	
	checkSelection: function() {
		if(this.selectedRows.length > 0) {
			$('tabDuplicate').style.display = 'block';
			if(this.selectedRows.length > 1) $('tabMultipleDelete').style.display = 'block';
			else $('tabMultipleDelete').style.display = 'none';
		} else {
			$('tabDuplicate').style.display = 'none';
			$('tabMultipleDelete').style.display = 'none';
		}
	},
	
	checkAllRows: function() {
		var inputs = $$('input[type="checkbox"].rowSelector');
		if(inputs[0].checked) var set = false;
		else var set = true;
		inputs.each(function(e){
			FF.contents.checkRow(e, set);
		});
	},
	
	duplicateRow: function(btn) {
		btn.innerHTML += '<img src="i/loading_bgBlue.gif" hspace="5">';
		btn.onclick = null;
		var ids = '';
		$A(this.selectedRows).each(function(e){
			ids += e.split("row_")[1]+',';
		});
		new Ajax.Request('inc/ajaxRequests.php?action=duplicateRows&ids='+ids+'&table='+FF.contents.table, {
			method: 'get',
			onComplete: FF.contents.duplicateRow_handler
		});
	},
	
	duplicateRow_handler: function(ajax) {
		Element.remove($$('#tabDuplicate img')[0]);
		if(ajax.responseText.indexOf('QUERY_ERROR') != -1) {
			alert("Problemi con la dupplicazione: " + ajax.responseText)
		} else {
			window.location.reload();
		}
	},
	
	multipleDelete: function(btn) {
		btn.innerHTML += '<img src="i/loading_bgBlue.gif" hspace="5">';
		btn.onclick = null;
		var ids = '';
		$A(this.selectedRows).each(function(e){
			ids += e.split("row_")[1]+',';
		});
		new Ajax.Request('inc/ajaxRequests.php?action=deleteMultipleRows&ids='+ids+'&table='+FF.contents.table, {
			method: 'get',
			onComplete: FF.contents.multipleDelete_handler
		});
	},
	
	multipleDelete_handler: function(ajax) {
		Element.remove($$('#tabMultipleDelete img')[0]);
		$A(FF.contents.selectedRows).each(function(e){
			$(e).style.display = 'none';
		});
		if(ajax.responseText.indexOf('QUERY_ERROR') != -1) {
			alert("Problemi con la cancellazione: " + ajax.responseText)
		} else {
			$('tabMultipleDelete').onclick = function(){FF.contents.multipleDelete(this);}
			$('tabMultipleDelete').style.display = 'none';
			FF.contents.selectedRows = new Array();
		}
	},
	
	showCalendar: function(calID) {
		$(calID).style.display = 'block';
	},
	
	getExcelDump: function(table) {
		this.excelDumping = table;
		new Ajax.Request('inc/ajaxRequests.php?action=makeExcelDump&table='+table, {
			method: 'get',
			onComplete: FF.contents.getExcelDump_handler
		});
	},
	
	getCSVDump: function(table) {
		this.excelDumping = table;
		new Ajax.Request('inc/ajaxRequests.php?action=makeCSVDump&table='+table, {
			method: 'get',
			onComplete: FF.contents.getCSVDump_handler
		});
	},
	
	getCSVDump_handler: function(ajax) {
		if(ajax.responseText.indexOf('OK') != -1) {
			var fileName = ajax.responseText.split('<filename>')[1];
			var content = Builder.node('DIV', {style: 'padding: 15px'});
			content.innerHTML = 'Il file CSV e\' scaricabile da qui: <a href="inc/'+fileName+'" target="_blank">SCARICA</a><br><br>Sara\' disponibile per una settimana.';
			Animations.Popup.create(200, 150, content, "DOM");
			
		} else {
			alert("ERROR creating CSV dump");
			alert(ajax.responseText);
		}
	},
	
	getExcelDump_handler: function(ajax) {
		if(ajax.responseText.indexOf('OK') != -1) {
			var fileName = ajax.responseText.split('<filename>')[1];
			var content = Builder.node('DIV', {style: 'padding: 15px'});
			content.innerHTML = 'Il file EXCEL e\' scaricabile da qui: <a href="inc/'+fileName+'" target="_blank">SCARICA</a><br><br>Sara\' disponibile per una settimana.';
			Animations.Popup.create(200, 150, content, "DOM");
			
		} else {
			alert("ERROR creating Excel dump");
			alert(ajax.responseText);
		}
	},
	
	runFilter: function(obj) {
		if(!Element.hasClassName(obj.parentNode, 'on')) {
			this.buildFilterConsole();
			$('tabContent').style.overflow = 'hidden';
			$('tabContent').style.display = 'block';
			Element.addClassName(obj.parentNode, 'on');
			Animations.yscale($('tabContent'), 50, .5);
		} else {
			Element.removeClassName(obj.parentNode, 'on');
			Animations.yscale($('tabContent'), 1, .3);
			Element.remove('filterBox');
		}
	},
	
	buildFilterConsole: function() {
		var filterBox = Builder.node('div', {id: 'filterBox'});
		filterBox.innerHTML = '<p>Loading...</p>';
		$('tabContent').appendChild(filterBox);
		new Ajax.Request('inc/ajaxRequests.php?action=getFilterConsole&table='+FF.contents.table, {
			method: 'get',
			onComplete: FF.contents.buildFilterConsole_handler
		});
	},
	
	buildFilterConsole_handler: function(ajax) {
		$('filterBox').innerHTML = ajax.responseText;
		Animations.yscale($('tabContent'), $('filterBox').offsetHeight + 20, .4);
	},
	
	runSearch: function(obj) {
		if(obj.className != 'on') {
			this.buildSearchConsole();
			$('tabContent').style.overflow = 'hidden';
			$('tabContent').style.display = 'block';
			obj.className = 'on';
			Animations.yscale($('tabContent'), 50, .5);
		} else {
			obj.className = 'off';
			//$('tabContent').innerHTML = '';
			Animations.yscale($('tabContent'), 1, .3);
		}
	},
	
	buildSearchConsole: function() {
		var searchBox = Builder.node('div', {id: 'searchBox'});
		searchBox.innerHTML = '<p>Loading...</p>';
		$('tabContent').appendChild(searchBox);
		new Ajax.Request('inc/ajaxRequests.php?action=getSearchConsole&table='+FF.contents.table, {
			method: 'get',
			onComplete: FF.contents.buildSearchConsole_handler
		});
	},
	
	buildSearchConsole_handler: function(ajax) {
		$('searchBox').innerHTML = ajax.responseText;
		Animations.yscale($('tabContent'), $('searchBox').offsetHeight + 20, .4);
	},
	
	showImagesThumb: function(field, path, w, btnIcon) {
		$$('td.imageField_' + field).each(function(elem){
			var imgName = elem.firstChild.innerHTML;
			elem.innerHTML = '<img src="'+path+imgName+'" width="'+w+'>';
		});
		btnIcon.down(0).src = btnIcon.down(0).src.split('view.gif').join('hide.gif');
		btnIcon.onclick = function() {
			FF.contents.hideImagesThumb(field, path, w, this);
		}
	},
	
	hideImagesThumb: function(field, path, w, btnIcon) {
		btnIcon.down(0).src = btnIcon.down(0).src.split('hide.gif').join('view.gif');
		$$('td.imageField_' + field).each(function(elem){
			elem.innerHTML = elem.down(0).src.split("/")[elem.down(0).src.split("/").length-1];
		});
		btnIcon.onclick = function() {
			FF.contents.showImagesThumb(field, path, w, this);
		}
	},
	
	selectFastImage: function(name, src, type, form) {
		this.changeImageSrc(name, src);
		if(!form) var form = document.editForm;
		form['loadingType_' + name].value = type;
		$('remove_' + name).value = '';
	},
	
	selectImage: function(name, src, type, form) {
		this.changeImageSrc(name, src);
		if(!form) var form = document.editForm;
		form['loadingType_' + name].value = type;
		$('remove_' + name).value = '';
	},
	
	changeImageSrc: function(id, src) {
		if(src != '') {
			$('previewer_' + id).src = src;
			$('filename_' + id).innerHTML = src;
			$('remove_' + id).value = '';
		}
	},
	
	removeUploadedFile: function(file, table, element) {
		this.removingField = element;
		this.removingFile = file;
		new Ajax.Request('inc/ajaxRequests.php?action=removeUploadedFile&fileName='+file+'&table=' + table, {
			method: 'get',
			onComplete: FF.contents.removeUploadedFile_handler
		});
	},
	
	removeUploadedFile_handler: function(AJAX) {
		if(AJAX.responseText.indexOf('OK') != -1) {
			$('previewer_' + FF.contents.removingField).src = 'i/imageNotFound.gif';
			$('filename_' + FF.contents.removingField).innerHTML = '-- rimosso --';
			$('remove_' + FF.contents.removingField).value = 'TRUE';
			Element.remove($('btnRemove_' + FF.contents.removingField));
			var sel = $('fileSelect_' + FF.contents.removingField);
			if(sel) Element.cleanWhitespace(sel);
			for(var i=0; i<sel.childNodes.length; i++) {
				if(sel.childNodes[i].value == FF.contents.removingFile) Element.remove(sel.childNodes[i]);
			}
		}
	},
	
	deleteRow: function(elemId, elemIdField, table) {
		if (confirm("Sei sicuro di voler cancellare questo dato?")) {
			window.location = 'dataProcessor.php?processACTION=DEL&idField='+elemIdField+'&id='+elemId+'&table='+table;
		} else {
			return false;
		}
	},
	
	closeCrossfieldPopup: function() {
		Animations.closePopup();		
	},
	
	
	closeVirtualCrossfieldPopup: function() {
		Animations.closePopup();		
	},
	
	closeFastEdit: function() {
		
		var obj = this.fastEditing.parentNode;
		Element.removeClassName(obj, 'fastEditing');
		
		Animations.closePopup();
		
	},
	
	fastEdit: function(elem) {
		
		// Cambio colore all'elemento in fast edit
		Element.addClassName(elem.parentNode, 'fastEditing');
		
		this.fastEditing = elem;
		this.updateFastediting = elem.id;
		
		var popup = FF.visual.createPopup();
		$('contents').appendChild(popup);
		
		Animations.showFastEditPopup(popup, elem);
		
	},
	
	refreshFastEdited: function() {
		var params = this.updateFastediting.split(">");
		var refresh = new Ajax.Request('inc/ajaxRequests.php?action=refreshFastEdited&table='+params[0]+'&id='+params[1]+'&campoGet='+params[2], {
			method: 'get',
			onComplete: FF.contents.handle_refreshFastEdited
		});
	},
	
	handle_refreshFastEdited: function(ajax) {
		var updateHTML = ajax.responseText.split("<htmlcode>")[1];
		if(updateHTML != 'KO' && ajax.responseText != "") {
			$(FF.contents.updateFastediting).innerHTML = updateHTML;
		}
	},
	
	saveFastEdit: function(href, form, closeAfterFinish) {
		
		this.closeAfterFinish = closeAfterFinish;
		var wait = Builder.node('IMG', {src: 'i/loading.gif', id: 'loadingIcon'});
		href.parentNode.insertBefore(wait, href.nextSibling);

		var save = new Ajax.Request('inc/ajaxRequests.php?action=saveFastEdit&'+form, {
			method: 'get',
			onComplete: FF.contents.handle_saveFastEdit
		});
	},
	
	handle_saveFastEdit: function(req) {
		if(req.responseText.indexOf('OK') != -1) {
			Element.remove('loadingIcon');
			parent.externalCall('FF.contents.refreshFastEdited();');
			
			if(FF.contents.closeAfterFinish) {
				parent.externalCall('FF.contents.closeFastEdit()');
			} else {
				var ok = Builder.node("DIV", {className: 'resultOK', id: 'resultOk'}, 'Salvato correttamente');
				$('popupButtonRow').insertBefore(ok, Element.cleanWhitespace($('popupButtonRow')).firstChild);
				new Effect.Pulsate('resultOk', { afterFinishInternal: function() {Element.remove('resultOk')}});
			}
			
		} else {
			alert("ERRORE: " + req.responseText);
		}
	},
	
	checkDataFormat: function(format, f) {
		switch (format) {
			case "NUMERIC": 
				if(isNaN(f.value)) {
					alert('Questo campo deve essere numerico');
					f.focus();
					f.style.border = '2px solid red';
				} else {
					f.style.border = '1px solid #333';
				}
				break;
			case "DATE": 
				var dates = f.value.split("-");
				if(dates.length != 3 || dates[0].length != 4 || dates[1].length != 2 || dates[2].length != 2) {
					alert('Questo campo deve essere nel formato: AAAA-MM-GG');
					f.focus();
					f.style.border = '2px solid red';
				} else {
					f.style.border = '1px solid #333';
				}
		}
	},
	
	RTA: function(f, type) {
		if(type == "advanced") {
			tinyMCE.init({
			  mode : "textareas",
			  theme : "advanced",
			  editor_selector : f,
			  plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,iespell,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
			  theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,fontsizeselect,pastetext,pasteword,|,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,code",
			  theme_advanced_buttons2 : "forecolor,backcolor,|,sub,sup,template,pagebreak",
			  theme_advanced_toolbar_location : "top",
			  theme_advanced_toolbar_align : "left",
			  theme_advanced_statusbar_location : "bottom",
			  theme_advanced_resizing : true
	   		});
		} else {
			tinyMCE.init({
			  mode : "textareas",
			  theme : "simple",
			  editor_selector : f,
			  theme_advanced_resizing : true
			});
		}
		/*
		var sBasePath = 'js/FCKeditor/';
		$(f).style.display = 'none';
		var txtArea = new FCKeditor(f);
		txtArea.BasePath = sBasePath;
		txtArea.ReplaceTextarea();
		*/
	},
	
	/*deleteRow: function(id, tabella, idField) {
		if(confirm('Sei sicuro di voler cancellare questo elemento?')){
			FF.contents.deletingRowId = idRow;
			new Ajax.Request('inc/ajax_lib.php?do=delTableElement&idRow='+idRow+'&id='+id+'&tabella='+tabella+'&idField='+idField, {onSuccess:FF.contents.deleteRowHandler});
			//do_callPHP(,'delTableElement','get')};
		}
	},*/
	
	deleteRowHandler: function(t) {
		for(var i=0; i<$(FF.contents.deletingRowId).childNodes.length; i++) {
			$(FF.contents.deletingRowId).childNodes[i].style.background = '#888';
			Element.setOpacity($(FF.contents.deletingRowId).childNodes[i], .35);
			$(FF.contents.deletingRowId).childNodes[i].innerHTML = '<div style="overflow:hidden;">XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</div>';
		}
		$(FF.contents.deletingRowId).childNodes[1].innerHTML = 'XX';
		$(FF.contents.deletingRowId).childNodes[2].innerHTML = 'XX';
	},

	CheckAll: function(tabella,idField) {
	  var check = false;
	  for (var i = 0; i < document.contentForm.elements.length; i++) {
		if(document.contentForm.elements[i].type == 'checkbox'){
			if(!document.contentForm.elements[i].checked) check = true;
		}
	  }
	  for (var i = 0; i < document.contentForm.elements.length; i++) {
		if(document.contentForm.elements[i].type == 'checkbox'){
		  document.contentForm.elements[i].checked = check;
		}
	  }
	  checkActions(tabella,idField);
	},
	
	uncheckAll: function() {
	  for (var i = 0; i < document.contentForm.elements.length; i++) {
		if(document.contentForm.elements[i].type == 'checkbox'){
		  document.contentForm.elements[i].checked = false;
		}
	  }
	  document.getElementById('actionMenu').style.visibility='hidden';
	},
	
	moveOptions: function(sel1,sel2,selReal,val) {
		//MUOVE I VALORI SELEZIONATI DALLA SEL1 ALLA SEL2
		//Ciclo i valori da spostare
		for(var i=0; i<sel1.length; i++) {
			if(sel1.options[i].selected) {
				var exists = false;
				for(var j=0; j<sel2.length; j++) {
					if(sel2.options[j].value == sel1.options[i].value) exists = true;
				}
				if(!exists) {
					//inserisco il valore nella select bersaglio e lo levo dall'altra
					var newOpt = new Option();
					newOpt.value = sel1.options[i].value;
					newOpt.text = sel1.options[i].text;
					sel2.options[sel2.options.length] = newOpt;
					
					sel1.options[i] = null;
				}
			}
		}
		// Valorizzo il campo nascosto
		var multiVal = "";
		for(var i=0; i<selReal.length; i++) {
			if(i==0) multiVal = selReal.options[i].value;
			else multiVal += "***" + selReal.options[i].value;
		}
		val.value = multiVal;
	},
	
	delOptions: function(sel2, val) {
		for(var i=sel2.length-1; i>=0; i--) if(sel2.options[i].selected) sel2.options[i] = null;
		
		// Valorizzo il campo nascosto
		var multiVal = "";
		for(var i=0; i<sel2.length; i++) {
			if(i==0) multiVal = sel2.options[i].value;
			else multiVal += "***" + sel2.options[i].value;
		}
		document.getElementById(val).value = multiVal;
	},
	
	SAVE: function() {
		document.editForm.submit();
	},
	
	SAVE_AND_REDO: function() {
		document.editForm.action = 'dataProcessor.php?action=doItAgain';
		this.SAVE();
	}
	
}


FF.configurator = {
	
	removeCrossField: function() {
		
	},
	
	setDataPerPage: function(table, num) {
		new Ajax.Request('inc/ajaxRequests.php?action=setDataPerPage&table='+table+'&num='+num, {
			method: 'get',
			onComplete: function(ajax) {window.location.reload();}
		});
	},
	
	showHide: function(div, btn) {
		if($('conf_messager_debug').style.display != 'block') {
			$('conf_messager_debug').style.display = 'block';
		}
		else $('conf_messager_debug').style.display = 'none';
	},
	
	removeUser: function(userName) {
		this.userDeleting = userName;
		new Ajax.Request('../inc/ajaxRequests.php?action=removeUser&userName='+userName, {
			method: 'get',
			onComplete: FF.configurator.removeUser_handler
		});
	},
	
	removeUser_handler: function(ajax) {
		if(ajax.responseText.indexOf('OK') != -1) {
			//$('userListSelect')
			for(var i=0; i<$('userListSelect').options.length; i++) {
				if($('userListSelect')[i].value == FF.configurator.userDeleting) Element.remove($('userListSelect')[i]);
			}
			$('userActionConsole').innerHTML += "<br><strong>Rimosso correttamente '" + FF.configurator.userDeleting + "'</strong>";
		}
	},
	
	editUserForm: function(sel) {
		if($('btnEditUser').style.display != 'inline') $('btnEditUser').style.display = 'inline';
		if($('btnRemoveUser').style.display != 'inline') $('btnRemoveUser').style.display = 'inline';
		$('btnEditUser').onclick = function() {
			Animations.showEditUserPopup(sel[sel.selectedIndex].value);
		}
	},
	
	memSelectedTables: function(sel, fieldID, sep) {
		var values = "";
		for(var i=0; i<sel.options.length; i++) {
			if(sel.options[i].selected) {
				values += sel.options[i].value;
				if(i < sel.options.length) values += sep;
			}
		}
		$(fieldID).value = values;
	},
	
	addNewUser: function() {
		Element.remove('newUserButton');
		$('newUserTable').style.display = 'block';
		document.configurator.addNewUser.value = 'true';
	},
	
	removeField: function(elem) {
		elem.parentNode.parentNode.parentNode.removeChild(elem.parentNode.parentNode);
		$('configurator_form').appendChild(Builder.node('input', {type: 'hidden', name:elem.id.split("_removeButton")[0]+"_remove"}));
	},
	
	addFieldSettingRow: function(t) {

		var filedsSel = $('fieldsSelect').cloneNode(true);
		filedsSel.id = 'fieldsSelector';
		
		var newRow = Builder.node('TR', {id: 'TEMP_FIELD_NAME_row'}, [
			Builder.node('TD', [
				Builder.node('INPUT', {type: 'hidden', name: 'TEMP_FIELD_NAME_name', id: 'TEMP_FIELD_NAME_name', value: 'TEMP_FIELD_NAME'}),
				Builder.node('INPUT', {type: 'button', id: 'TEMP_FIELD_NAME_removeButton', name: 'TEMP_FIELD_NAME_removeButton', value: 'remove', onclick: 'function(){FF.configurator.removeField(this);}'})
			]),
			Builder.node('TD', {className: 'fieldName'}, [filedsSel]),
			Builder.node('TD', [
				Builder.node('INPUT', {type: 'text', name: 'TEMP_FIELD_NAME_title', id: 'TEMP_FIELD_NAME_title', value: ''})
			]),
			Builder.node('TD', {align: 'center'}, [
				Builder.node('SELECT', {name: 'TEMP_FIELD_NAME_visible', id: 'TEMP_FIELD_NAME_visible'}, [
					Builder.node('OPTION', {value: 'false'}, 'NO'),
					Builder.node('OPTION', {value: 'true'}, 'SI')
				])
			]),
			Builder.node('TD', {align: 'center'}, [
				Builder.node('SELECT', {name: 'TEMP_FIELD_NAME_adminField', id: 'TEMP_FIELD_NAME_adminField'}, [
					Builder.node('OPTION', {value: 'true'}, 'SI'),
					Builder.node('OPTION', {value: 'false'}, 'NO')
				])
			]),
			Builder.node('TD', {align: 'center'}, [
				Builder.node('SELECT', {name: 'TEMP_FIELD_NAME_multiple', id: 'TEMP_FIELD_NAME_multiple'}, [
					Builder.node('OPTION', {value: 'true'}, 'SI'),
					Builder.node('OPTION', {value: 'false'}, 'NO')
				])
			]),
			Builder.node('TD', {align: 'center'}, [
				Builder.node('SELECT', {name: 'TEMP_FIELD_NAME_type', id: 'TEMP_FIELD_NAME_type'}, [
					Builder.node('OPTION', {value: 'filesystem'}, 'Filesystem'),
					Builder.node('OPTION', {value: 'Database'}, 'Database')
				])
			]),
			Builder.node('TD', {align: 'center'}, [
				Builder.node('DIV', {style: 'display: inline', id: 'TEMP_FIELD_NAME_cross'}, 'NO '),
				Builder.node('a', {href: '#'}, '(i)')
			]),
			Builder.node('TD', {align: 'center'}, [
				Builder.node('DIV', {style: 'display: inline', id: 'TEMP_FIELD_NAME_virtualCross'}, 'NO '),
				Builder.node('a', {href: '#'}, '(i)')
			]),
		]);
		newRow.firstChild.firstChild.onclick = function() {
			FF.configurator.removeField(this);
		}
		$('newFieldsRowTable').appendChild(newRow);
		$('TEMP_FIELD_NAME_cross').onclick = function() {
			Animations.showCrossfieldPopup(this.parentNode.parentNode.id.split("_row")[0]);
		}
		$('fieldsSelector').onchange = function() {FF.configurator.setNewRowId(this);}
	},
	
	setNewRowId: function(elem) {
		
		var field = elem.options[elem.selectedIndex].value;
		if(!$(field + '_row')) {
			
			$('TEMP_FIELD_NAME_row').id = field + '_row';
			$('TEMP_FIELD_NAME_removeButton').name = $('TEMP_FIELD_NAME_removeButton').id = field + '_remove';
			$('TEMP_FIELD_NAME_title').name = $('TEMP_FIELD_NAME_title').id = field + '_title';
			$('TEMP_FIELD_NAME_name').name = $('TEMP_FIELD_NAME_name').id = field + '_name';
			$(field + '_name').value = field;
			$('TEMP_FIELD_NAME_visible').name = $('TEMP_FIELD_NAME_visible').id = field + '_visible';
			$('TEMP_FIELD_NAME_adminField').name = $('TEMP_FIELD_NAME_adminField').id = field + '_adminField';
			$('TEMP_FIELD_NAME_multiple').name = $('TEMP_FIELD_NAME_multiple').id = field + '_multiple';
			$('TEMP_FIELD_NAME_type').name = $('TEMP_FIELD_NAME_type').id = field + '_type';
			$('TEMP_FIELD_NAME_cross').name = $('TEMP_FIELD_NAME_cross').id = field + '_cross';
			$('TEMP_FIELD_NAME_virtualCross').name = $('TEMP_FIELD_NAME_virtualCross').id = field + '_virtualCross';
			
		}
		
	},
	
	removePlugin: function(row, name) {
		Element.remove(row.parentNode.parentNode);
		if(name != null) {
			// Era stato impostato, devo impostare la cancellazione
			name = name.split(" ").join("");
			$('configurator_form').appendChild(Builder.node('input', {type: 'hidden', name: 'plugin_' + name + '_remove', value: name}));
		}
	},
	
	addPluginRow: function() {
		new Ajax.Request('../inc/ajaxRequests.php?action=getPlugins&index='+$('pluginTable').childNodes.length, {
			method: 'get',
			onComplete: FF.configurator.addPluginRow_handler
		});
	},
	
	addPluginRow_handler: function(ajax) {
		$('pluginTable').innerHTML += ajax.responseText;
	}
	
}

FF.EventManager = {
	
	/*   NOT USED
	removeDocumentClickAction: function(f) {
		FF.ClickActions = FF.ClickActions.without(f);
	},
	*/
	
	addDocumentClickAction: function(f) {
		FF.ClickActions.push(f);
	},	
	
	runDocumentClickAction: function(e) {
		FF.ClickActions.each(function(f, i){
			eval(f);
		});
	},
	
	runKeyMapper: function(e) {
		if(!FF.EventManager.pressed) {
			FF.EventManager.pressed = true;
			var intID = setInterval(function(){
				clearInterval(intID);
				FF.EventManager.pressed = false;
				FF.EventManager.singleKeyPress(e);
			}, 350);
		} else {
			clearInterval(intID);
			FF.EventManager.pressed = false;
			FF.EventManager.doubleKeyPress(e);
		}
	},
	
	singleKeyPress: function() {},
	
	doubleKeyPress: function(e) {
		if(e.keyCode == Event.KEY_TAB) {
			var menuWidth = parent.document.getElementById('FFcontentWindow').getAttribute('cols').split(",")[0];
			var headerHeight = parent.document.getElementById('FFWindow').getAttribute('rows').split(",")[0];
			if(Number(menuWidth) > 1) FF.visual.enlargeViewport(menuWidth, headerHeight);
			else FF.visual.resetViewport();
		} else {
			var code;
			if (!e) var e = window.event;
			if (e.keyCode) code = e.keyCode;
			else if (e.which) code = e.which;
			var _char = String.fromCharCode(code);
			switch(_char) {
				case 'm': 
					if(FF.visual.viewportStatus == 'enlarged') {
						Animations.Popup.prepareFog();
					}
					break;
			}
		}
	}
	
}

FF.Utils = {
	
	getLocationAndAppend: function(append) {
		var loc = window.location.href;
		if(loc.endsWith('#')) loc = loc.truncate(loc.length-1, '');
		if(append != null) return loc+append;
	},
	
	storedValues: {},
	
	getWindowSize: function() 
	{
		return document.viewport.getDimensions();
	},
	
	cleanValue: function(f, options)
	{
		if(options.restoreAfterBlur) {
			this.storedValues[Element.identify(f)] = options.defaultValue || f.value;
		}			
		f.value = '';
		f.onblur = function() {
			if(this.value == '') {
				this.value = Utils.storedValues[this.identify()];
				this.onclick = function() {
					Utils.cleanValue(this, {restoreAfterBlur: true});
				}
			}
			else 
				this.onclick = null;
		}
	},
	
	resetSelect: function(select, option) 
	{
		if($(select) && $(select).nodeName == 'SELECT') select = $(select);
		if (select) {
			var to = option.to || select.childElements().length;
			var from = option.from || 0;
			for (var i = to; i > from; i--) {
				$('RadioContent').innerHTML += 'Cancello da ' + select.innerHTML + ' l\'id ' + i + ' (<strong>'+select[(i-1)].innerHTML+'</strong> - from: '+from+')<br><br>';
				Element.remove(select[(i-1)]);
			}
		}
	},
	
	getSelect: function(select) 
	{
		if($(select) && $(select).nodeName == 'SELECT') select = $(select);
		if (select) {
			return {value: select.options[select.selectedIndex].value, label: select.options[select.selectedIndex].text}
		}
	},
	
	initFlashProxy: function(uid) 
	{
		return new FlashProxy(uid, 'js/JavaScriptFlashGateway.swf');
	},
	
	writeFlash: function(src, options) {
		var my_var = '<object type="application/x-shockwave-flash" data="' + src + '" width="' + options.w + '" height="' + options.h + '">';
		if(options.flashVars != null) my_var += '<param name="flashvars" value="' + options.flashVars + '" />';
		my_var += '<param name="movie" value="' + src + '" />';
		my_var += '<param name="quality" value="high" />';
		if(options.transparent == true)
			my_var += '<param name="wmode" value="transparent" />';
		my_var += '</object>';
		if(options.updateElement != null && options.updateElement != false) {
			if(options.updateType == 'top') 
				$(options.updateElement).innerHTML = my_var + $(options.updateElement).innerHTML;
			else 
				$(options.updateElement).innerHTML += my_var;
		}
		else 
			document.write(my_var);
	},
	
	setCookie: function (name, val, expDays)
	{
		var exp = new Date(); 
		exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
		expDate=exp.toGMTString();
		document.cookie = ""+name+" ="+ val+"; expires ="+ expDate+";";
	},
	
	getCookie: function (offset)
	{ 
		offset = offset + '=';
		if(document.cookie.indexOf(offset) > -1) {
			return document.cookie.split(offset)[1].split(';')[0];
		} else 
			return false;
	},
	
	log: function (t)
	{
		$('Debug').innerHTML += "log> " + t + "<br />";
	},
	
	Alert: function(code)
	{
		alert(code);
	}
	
}



window.onload = function() {
	FF.initPage();
}


/* Funzioni per chiamate extra-finestra. Al momento non riesco a richiamarle con FF.contents.xxxxx */
function externalCall(f) {
	eval(f);
}
